home *** CD-ROM | disk | FTP | other *** search
/ Chip 2007 January, February, March & April / Chip-Cover-CD-2007-02.iso / Pakiet bezpieczenstwa / mini Pentoo LiveCD 2006.1 / mpentoo-2006.1.iso / livecd.squashfs / usr / lib / python2.4 / test / test_cookielib.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2005-10-18  |  46KB  |  1,279 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.4)
  3.  
  4. '''Tests for cookielib.py.'''
  5. import re
  6. import os
  7. import time
  8. from unittest import TestCase
  9. from test import test_support
  10.  
  11. class DateTimeTests(TestCase):
  12.     
  13.     def test_time2isoz(self):
  14.         time2isoz = time2isoz
  15.         import cookielib
  16.         base = 1019227000
  17.         day = 24 * 3600
  18.         self.assertEquals(time2isoz(base), '2002-04-19 14:36:40Z')
  19.         self.assertEquals(time2isoz(base + day), '2002-04-20 14:36:40Z')
  20.         self.assertEquals(time2isoz(base + 2 * day), '2002-04-21 14:36:40Z')
  21.         self.assertEquals(time2isoz(base + 3 * day), '2002-04-22 14:36:40Z')
  22.         az = time2isoz()
  23.         bz = time2isoz(500000)
  24.         for text in (az, bz):
  25.             self.assert_(re.search('^\\d{4}-\\d\\d-\\d\\d \\d\\d:\\d\\d:\\d\\dZ$', text), 'bad time2isoz format: %s %s' % (az, bz))
  26.         
  27.  
  28.     
  29.     def test_http2time(self):
  30.         http2time = http2time
  31.         import cookielib
  32.         
  33.         def parse_date(text):
  34.             return time.gmtime(http2time(text))[:6]
  35.  
  36.         self.assertEquals(parse_date('01 Jan 2001'), (2001, 1, 1, 0, 0, 0.0))
  37.         self.assertEquals(parse_date('03-Feb-20'), (2020, 2, 3, 0, 0, 0.0))
  38.         self.assertEquals(parse_date('03-Feb-98'), (1998, 2, 3, 0, 0, 0.0))
  39.  
  40.     
  41.     def test_http2time_formats(self):
  42.         http2time = http2time
  43.         time2isoz = time2isoz
  44.         import cookielib
  45.         tests = [
  46.             'Thu, 03 Feb 1994 00:00:00 GMT',
  47.             'Thursday, 03-Feb-94 00:00:00 GMT',
  48.             'Thursday, 03-Feb-1994 00:00:00 GMT',
  49.             '03 Feb 1994 00:00:00 GMT',
  50.             '03-Feb-94 00:00:00 GMT',
  51.             '03-Feb-1994 00:00:00 GMT',
  52.             '03-Feb-1994 00:00 GMT',
  53.             '03-Feb-1994 00:00',
  54.             '03-Feb-94',
  55.             '03-Feb-1994',
  56.             '03 Feb 1994',
  57.             '  03   Feb   1994  0:00  ',
  58.             '  03-Feb-1994  ']
  59.         test_t = 760233600
  60.         result = time2isoz(test_t)
  61.         expected = '1994-02-03 00:00:00Z'
  62.         self.assertEquals(result, expected, "%s  =>  '%s' (%s)" % (test_t, result, expected))
  63.         for s in tests:
  64.             t = http2time(s)
  65.             t2 = http2time(s.lower())
  66.             t3 = http2time(s.upper())
  67.             None(self.assert_ if t2 == t2 and t3 == t3 else t3 == test_t, "'%s'  =>  %s, %s, %s (%s)" % (s, t, t2, t3, test_t))
  68.         
  69.  
  70.     
  71.     def test_http2time_garbage(self):
  72.         http2time = http2time
  73.         import cookielib
  74.         for test in [
  75.             '',
  76.             'Garbage',
  77.             'Mandag 16. September 1996',
  78.             '01-00-1980',
  79.             '01-13-1980',
  80.             '00-01-1980',
  81.             '32-01-1980',
  82.             '01-01-1980 25:00:00',
  83.             '01-01-1980 00:61:00',
  84.             '01-01-1980 00:00:62']:
  85.             self.assert_(http2time(test) is None, 'http2time(%s) is not None\nhttp2time(test) %s' % (test, http2time(test)))
  86.         
  87.  
  88.  
  89.  
  90. class HeaderTests(TestCase):
  91.     
  92.     def test_parse_ns_headers(self):
  93.         parse_ns_headers = parse_ns_headers
  94.         import cookielib
  95.         expected = [
  96.             [
  97.                 ('foo', 'bar'),
  98.                 ('expires', 0x83ABB964L),
  99.                 ('version', '0')]]
  100.         for hdr in [
  101.             'foo=bar; expires=01 Jan 2040 22:23:32 GMT',
  102.             'foo=bar; expires="01 Jan 2040 22:23:32 GMT"']:
  103.             self.assertEquals(parse_ns_headers([
  104.                 hdr]), expected)
  105.         
  106.  
  107.     
  108.     def test_parse_ns_headers_special_names(self):
  109.         parse_ns_headers = parse_ns_headers
  110.         import cookielib
  111.         hdr = 'expires=01 Jan 2040 22:23:32 GMT'
  112.         expected = [
  113.             [
  114.                 ('expires', '01 Jan 2040 22:23:32 GMT'),
  115.                 ('version', '0')]]
  116.         self.assertEquals(parse_ns_headers([
  117.             hdr]), expected)
  118.  
  119.     
  120.     def test_join_header_words(self):
  121.         join_header_words = join_header_words
  122.         import cookielib
  123.         joined = join_header_words([
  124.             [
  125.                 ('foo', None),
  126.                 ('bar', 'baz')]])
  127.         self.assertEquals(joined, 'foo; bar=baz')
  128.         self.assertEquals(join_header_words([
  129.             []]), '')
  130.  
  131.     
  132.     def test_split_header_words(self):
  133.         split_header_words = split_header_words
  134.         import cookielib
  135.         tests = [
  136.             ('foo', [
  137.                 [
  138.                     ('foo', None)]]),
  139.             ('foo=bar', [
  140.                 [
  141.                     ('foo', 'bar')]]),
  142.             ('   foo   ', [
  143.                 [
  144.                     ('foo', None)]]),
  145.             ('   foo=   ', [
  146.                 [
  147.                     ('foo', '')]]),
  148.             ('   foo=', [
  149.                 [
  150.                     ('foo', '')]]),
  151.             ('   foo=   ; ', [
  152.                 [
  153.                     ('foo', '')]]),
  154.             ('   foo=   ; bar= baz ', [
  155.                 [
  156.                     ('foo', ''),
  157.                     ('bar', 'baz')]]),
  158.             ('foo=bar bar=baz', [
  159.                 [
  160.                     ('foo', 'bar'),
  161.                     ('bar', 'baz')]]),
  162.             ('foo= bar=baz', [
  163.                 [
  164.                     ('foo', 'bar=baz')]]),
  165.             ('foo=bar;bar=baz', [
  166.                 [
  167.                     ('foo', 'bar'),
  168.                     ('bar', 'baz')]]),
  169.             ('foo bar baz', [
  170.                 [
  171.                     ('foo', None),
  172.                     ('bar', None),
  173.                     ('baz', None)]]),
  174.             ('a, b, c', [
  175.                 [
  176.                     ('a', None)],
  177.                 [
  178.                     ('b', None)],
  179.                 [
  180.                     ('c', None)]]),
  181.             ('foo; bar=baz, spam=, foo="\\,\\;\\"", bar= ', [
  182.                 [
  183.                     ('foo', None),
  184.                     ('bar', 'baz')],
  185.                 [
  186.                     ('spam', '')],
  187.                 [
  188.                     ('foo', ',;"')],
  189.                 [
  190.                     ('bar', '')]])]
  191.         for arg, expect in tests:
  192.             
  193.             try:
  194.                 result = split_header_words([
  195.                     arg])
  196.             except:
  197.                 import traceback as traceback
  198.                 import StringIO as StringIO
  199.                 f = StringIO.StringIO()
  200.                 traceback.print_exc(None, f)
  201.                 result = '(error -- traceback follows)\n\n%s' % f.getvalue()
  202.  
  203.             self.assertEquals(result, expect, "\nWhen parsing: '%s'\nExpected:     '%s'\nGot:          '%s'\n" % (arg, expect, result))
  204.         
  205.  
  206.     
  207.     def test_roundtrip(self):
  208.         split_header_words = split_header_words
  209.         join_header_words = join_header_words
  210.         import cookielib
  211.         tests = [
  212.             ('foo', 'foo'),
  213.             ('foo=bar', 'foo=bar'),
  214.             ('   foo   ', 'foo'),
  215.             ('foo=', 'foo=""'),
  216.             ('foo=bar bar=baz', 'foo=bar; bar=baz'),
  217.             ('foo=bar;bar=baz', 'foo=bar; bar=baz'),
  218.             ('foo bar baz', 'foo; bar; baz'),
  219.             ('foo="\\"" bar="\\\\"', 'foo="\\""; bar="\\\\"'),
  220.             ('foo,,,bar', 'foo, bar'),
  221.             ('foo=bar,bar=baz', 'foo=bar, bar=baz'),
  222.             ('text/html; charset=iso-8859-1', 'text/html; charset="iso-8859-1"'),
  223.             ('foo="bar"; port="80,81"; discard, bar=baz', 'foo=bar; port="80,81"; discard, bar=baz'),
  224.             ('Basic realm="\\"foo\\\\\\\\bar\\""', 'Basic; realm="\\"foo\\\\\\\\bar\\""')]
  225.         for arg, expect in tests:
  226.             input = split_header_words([
  227.                 arg])
  228.             res = join_header_words(input)
  229.             self.assertEquals(res, expect, "\nWhen parsing: '%s'\nExpected:     '%s'\nGot:          '%s'\nInput was:    '%s'\n" % (arg, expect, res, input))
  230.         
  231.  
  232.  
  233.  
  234. class FakeResponse:
  235.     
  236.     def __init__(self, headers = [], url = None):
  237.         """
  238.         headers: list of RFC822-style 'Key: value' strings
  239.         """
  240.         import mimetools as mimetools
  241.         import StringIO
  242.         f = StringIO.StringIO('\n'.join(headers))
  243.         self._headers = mimetools.Message(f)
  244.         self._url = url
  245.  
  246.     
  247.     def info(self):
  248.         return self._headers
  249.  
  250.  
  251.  
  252. def interact_2965(cookiejar, url, *set_cookie_hdrs):
  253.     return _interact(cookiejar, url, set_cookie_hdrs, 'Set-Cookie2')
  254.  
  255.  
  256. def interact_netscape(cookiejar, url, *set_cookie_hdrs):
  257.     return _interact(cookiejar, url, set_cookie_hdrs, 'Set-Cookie')
  258.  
  259.  
  260. def _interact(cookiejar, url, set_cookie_hdrs, hdr_name):
  261.     '''Perform a single request / response cycle, returning Cookie: header.'''
  262.     Request = Request
  263.     import urllib2
  264.     req = Request(url)
  265.     cookiejar.add_cookie_header(req)
  266.     cookie_hdr = req.get_header('Cookie', '')
  267.     headers = []
  268.     for hdr in set_cookie_hdrs:
  269.         headers.append('%s: %s' % (hdr_name, hdr))
  270.     
  271.     res = FakeResponse(headers, url)
  272.     cookiejar.extract_cookies(res, req)
  273.     return cookie_hdr
  274.  
  275.  
  276. class FileCookieJarTests(TestCase):
  277.     
  278.     def test_lwp_valueless_cookie(self):
  279.         LWPCookieJar = LWPCookieJar
  280.         import cookielib
  281.         filename = test_support.TESTFN
  282.         c = LWPCookieJar()
  283.         interact_netscape(c, 'http://www.acme.com/', 'boo')
  284.         self.assertEqual(c._cookies['www.acme.com']['/']['boo'].value, None)
  285.         
  286.         try:
  287.             c.save(filename, ignore_discard = True)
  288.             c = LWPCookieJar()
  289.             c.load(filename, ignore_discard = True)
  290.         finally:
  291.             
  292.             try:
  293.                 os.unlink(filename)
  294.             except OSError:
  295.                 pass
  296.  
  297.  
  298.         self.assertEqual(c._cookies['www.acme.com']['/']['boo'].value, None)
  299.  
  300.  
  301.  
  302. class CookieTests(TestCase):
  303.     
  304.     def test_domain_return_ok(self):
  305.         import cookielib
  306.         import urllib2
  307.         pol = cookielib.DefaultCookiePolicy()
  308.         for url, domain, ok in [
  309.             ('http://foo.bar.com/', 'blah.com', False),
  310.             ('http://foo.bar.com/', 'rhubarb.blah.com', False),
  311.             ('http://foo.bar.com/', 'rhubarb.foo.bar.com', False),
  312.             ('http://foo.bar.com/', '.foo.bar.com', True),
  313.             ('http://foo.bar.com/', 'foo.bar.com', True),
  314.             ('http://foo.bar.com/', '.bar.com', True),
  315.             ('http://foo.bar.com/', 'com', True),
  316.             ('http://foo.com/', 'rhubarb.foo.com', False),
  317.             ('http://foo.com/', '.foo.com', True),
  318.             ('http://foo.com/', 'foo.com', True),
  319.             ('http://foo.com/', 'com', True),
  320.             ('http://foo/', 'rhubarb.foo', False),
  321.             ('http://foo/', '.foo', True),
  322.             ('http://foo/', 'foo', True),
  323.             ('http://foo/', 'foo.local', True),
  324.             ('http://foo/', '.local', True)]:
  325.             request = urllib2.Request(url)
  326.             r = pol.domain_return_ok(domain, request)
  327.             if ok:
  328.                 self.assert_(r)
  329.                 continue
  330.             self.assert_(not r)
  331.         
  332.  
  333.     
  334.     def test_missing_value(self):
  335.         MozillaCookieJar = MozillaCookieJar
  336.         lwp_cookie_str = lwp_cookie_str
  337.         import cookielib
  338.         filename = test_support.TESTFN
  339.         c = MozillaCookieJar(filename)
  340.         interact_netscape(c, 'http://www.acme.com/', 'eggs')
  341.         interact_netscape(c, 'http://www.acme.com/', '"spam"; path=/foo/')
  342.         cookie = c._cookies['www.acme.com']['/']['eggs']
  343.         self.assert_(cookie.value is None)
  344.         self.assertEquals(cookie.name, 'eggs')
  345.         cookie = c._cookies['www.acme.com']['/foo/']['"spam"']
  346.         self.assert_(cookie.value is None)
  347.         self.assertEquals(cookie.name, '"spam"')
  348.         self.assertEquals(lwp_cookie_str(cookie), '"spam"; path="/foo/"; domain="www.acme.com"; path_spec; discard; version=0')
  349.         old_str = repr(c)
  350.         c.save(ignore_expires = True, ignore_discard = True)
  351.         
  352.         try:
  353.             c = MozillaCookieJar(filename)
  354.             c.revert(ignore_expires = True, ignore_discard = True)
  355.         finally:
  356.             os.unlink(c.filename)
  357.  
  358.         self.assertEquals(repr(c), re.sub('path_specified=%s' % True, 'path_specified=%s' % False, old_str))
  359.         self.assertEquals(interact_netscape(c, 'http://www.acme.com/foo/'), '"spam"; eggs')
  360.  
  361.     
  362.     def test_ns_parser(self):
  363.         CookieJar = CookieJar
  364.         DEFAULT_HTTP_PORT = DEFAULT_HTTP_PORT
  365.         import cookielib
  366.         c = CookieJar()
  367.         interact_netscape(c, 'http://www.acme.com/', 'spam=eggs; DoMain=.acme.com; port; blArgh="feep"')
  368.         interact_netscape(c, 'http://www.acme.com/', 'ni=ni; port=80,8080')
  369.         interact_netscape(c, 'http://www.acme.com:80/', 'nini=ni')
  370.         interact_netscape(c, 'http://www.acme.com:80/', 'foo=bar; expires=')
  371.         interact_netscape(c, 'http://www.acme.com:80/', 'spam=eggs; expires="Foo Bar 25 33:22:11 3022"')
  372.         cookie = c._cookies['.acme.com']['/']['spam']
  373.         self.assertEquals(cookie.domain, '.acme.com')
  374.         self.assert_(cookie.domain_specified)
  375.         self.assertEquals(cookie.port, DEFAULT_HTTP_PORT)
  376.         self.assert_(not (cookie.port_specified))
  377.         if cookie.has_nonstandard_attr('blArgh'):
  378.             pass
  379.         self.assert_(not cookie.has_nonstandard_attr('blargh'))
  380.         cookie = c._cookies['www.acme.com']['/']['ni']
  381.         self.assertEquals(cookie.domain, 'www.acme.com')
  382.         self.assert_(not (cookie.domain_specified))
  383.         self.assertEquals(cookie.port, '80,8080')
  384.         self.assert_(cookie.port_specified)
  385.         cookie = c._cookies['www.acme.com']['/']['nini']
  386.         self.assert_(cookie.port is None)
  387.         self.assert_(not (cookie.port_specified))
  388.         foo = c._cookies['www.acme.com']['/']['foo']
  389.         spam = c._cookies['www.acme.com']['/']['foo']
  390.         self.assert_(foo.expires is None)
  391.         self.assert_(spam.expires is None)
  392.  
  393.     
  394.     def test_ns_parser_special_names(self):
  395.         CookieJar = CookieJar
  396.         import cookielib
  397.         c = CookieJar()
  398.         interact_netscape(c, 'http://www.acme.com/', 'expires=eggs')
  399.         interact_netscape(c, 'http://www.acme.com/', 'version=eggs; spam=eggs')
  400.         cookies = c._cookies['www.acme.com']['/']
  401.         self.assert_('expires' in cookies)
  402.         self.assert_('version' in cookies)
  403.  
  404.     
  405.     def test_expires(self):
  406.         time2netscape = time2netscape
  407.         CookieJar = CookieJar
  408.         import cookielib
  409.         c = CookieJar()
  410.         future = time2netscape(time.time() + 3600)
  411.         interact_netscape(c, 'http://www.acme.com/', 'spam="bar"; expires=%s' % future)
  412.         self.assertEquals(len(c), 1)
  413.         now = time2netscape(time.time() - 1)
  414.         interact_netscape(c, 'http://www.acme.com/', 'foo="eggs"; expires=%s' % now)
  415.         h = interact_netscape(c, 'http://www.acme.com/')
  416.         self.assertEquals(len(c), 1)
  417.         if 'spam="bar"' in h:
  418.             pass
  419.         self.assert_('foo' not in h)
  420.         interact_netscape(c, 'http://www.acme.com/', 'eggs="bar"; expires=%s' % future)
  421.         interact_netscape(c, 'http://www.acme.com/', 'bar="bar"; expires=%s' % future)
  422.         self.assertEquals(len(c), 3)
  423.         interact_netscape(c, 'http://www.acme.com/', 'eggs="bar"; expires=%s; max-age=0' % future)
  424.         interact_netscape(c, 'http://www.acme.com/', 'bar="bar"; max-age=0; expires=%s' % future)
  425.         h = interact_netscape(c, 'http://www.acme.com/')
  426.         self.assertEquals(len(c), 1)
  427.         interact_netscape(c, 'http://www.rhubarb.net/', 'whum="fizz"')
  428.         self.assertEquals(len(c), 2)
  429.         c.clear_session_cookies()
  430.         self.assertEquals(len(c), 1)
  431.         self.assert_('spam="bar"' in h)
  432.  
  433.     
  434.     def test_default_path(self):
  435.         CookieJar = CookieJar
  436.         DefaultCookiePolicy = DefaultCookiePolicy
  437.         import cookielib
  438.         pol = DefaultCookiePolicy(rfc2965 = True)
  439.         c = CookieJar(pol)
  440.         interact_2965(c, 'http://www.acme.com/', 'spam="bar"; Version="1"')
  441.         self.assert_('/' in c._cookies['www.acme.com'])
  442.         c = CookieJar(pol)
  443.         interact_2965(c, 'http://www.acme.com/blah', 'eggs="bar"; Version="1"')
  444.         self.assert_('/' in c._cookies['www.acme.com'])
  445.         c = CookieJar(pol)
  446.         interact_2965(c, 'http://www.acme.com/blah/rhubarb', 'eggs="bar"; Version="1"')
  447.         self.assert_('/blah/' in c._cookies['www.acme.com'])
  448.         c = CookieJar(pol)
  449.         interact_2965(c, 'http://www.acme.com/blah/rhubarb/', 'eggs="bar"; Version="1"')
  450.         self.assert_('/blah/rhubarb/' in c._cookies['www.acme.com'])
  451.         c = CookieJar()
  452.         interact_netscape(c, 'http://www.acme.com/', 'spam="bar"')
  453.         self.assert_('/' in c._cookies['www.acme.com'])
  454.         c = CookieJar()
  455.         interact_netscape(c, 'http://www.acme.com/blah', 'eggs="bar"')
  456.         self.assert_('/' in c._cookies['www.acme.com'])
  457.         c = CookieJar()
  458.         interact_netscape(c, 'http://www.acme.com/blah/rhubarb', 'eggs="bar"')
  459.         self.assert_('/blah' in c._cookies['www.acme.com'])
  460.         c = CookieJar()
  461.         interact_netscape(c, 'http://www.acme.com/blah/rhubarb/', 'eggs="bar"')
  462.         self.assert_('/blah/rhubarb' in c._cookies['www.acme.com'])
  463.  
  464.     
  465.     def test_escape_path(self):
  466.         escape_path = escape_path
  467.         import cookielib
  468.         cases = [
  469.             ('/foo%2f/bar', '/foo%2F/bar'),
  470.             ('/foo%2F/bar', '/foo%2F/bar'),
  471.             ('/foo%%/bar', '/foo%%/bar'),
  472.             ('/fo%19o/bar', '/fo%19o/bar'),
  473.             ('/fo%7do/bar', '/fo%7Do/bar'),
  474.             ('/foo/bar&', '/foo/bar&'),
  475.             ('/foo//bar', '/foo//bar'),
  476.             ('~/foo/bar', '~/foo/bar'),
  477.             ('/foo\x19/bar', '/foo%19/bar'),
  478.             ('/}foo/bar', '/%7Dfoo/bar'),
  479.             (u'/foo/bar\xea\xaf\x8d', '/foo/bar%EA%AF%8D')]
  480.         for arg, result in cases:
  481.             self.assertEquals(escape_path(arg), result)
  482.         
  483.  
  484.     
  485.     def test_request_path(self):
  486.         Request = Request
  487.         import urllib2
  488.         request_path = request_path
  489.         import cookielib
  490.         req = Request('http://www.example.com/rheum/rhaponicum;foo=bar;sing=song?apples=pears&spam=eggs#ni')
  491.         self.assertEquals(request_path(req), '/rheum/rhaponicum;foo=bar;sing=song?apples=pears&spam=eggs#ni')
  492.         req = Request('http://www.example.com/rheum/rhaponicum?apples=pears&spam=eggs#ni')
  493.         self.assertEquals(request_path(req), '/rheum/rhaponicum?apples=pears&spam=eggs#ni')
  494.         req = Request('http://www.example.com')
  495.         self.assertEquals(request_path(req), '/')
  496.  
  497.     
  498.     def test_request_port(self):
  499.         Request = Request
  500.         import urllib2
  501.         request_port = request_port
  502.         DEFAULT_HTTP_PORT = DEFAULT_HTTP_PORT
  503.         import cookielib
  504.         req = Request('http://www.acme.com:1234/', headers = {
  505.             'Host': 'www.acme.com:4321' })
  506.         self.assertEquals(request_port(req), '1234')
  507.         req = Request('http://www.acme.com/', headers = {
  508.             'Host': 'www.acme.com:4321' })
  509.         self.assertEquals(request_port(req), DEFAULT_HTTP_PORT)
  510.  
  511.     
  512.     def test_request_host(self):
  513.         Request = Request
  514.         import urllib2
  515.         request_host = request_host
  516.         import cookielib
  517.         req = Request('http://1.1.1.1/', headers = {
  518.             'Host': 'www.acme.com:80' })
  519.         self.assertEquals(request_host(req), '1.1.1.1')
  520.         req = Request('http://www.acme.com/', headers = {
  521.             'Host': 'irrelevant.com' })
  522.         self.assertEquals(request_host(req), 'www.acme.com')
  523.         req = Request('/resource.html', headers = {
  524.             'Host': 'www.acme.com' })
  525.         self.assertEquals(request_host(req), 'www.acme.com')
  526.         req = Request('http://www.acme.com:2345/resource.html', headers = {
  527.             'Host': 'www.acme.com:5432' })
  528.         self.assertEquals(request_host(req), 'www.acme.com')
  529.  
  530.     
  531.     def test_is_HDN(self):
  532.         is_HDN = is_HDN
  533.         import cookielib
  534.         self.assert_(is_HDN('foo.bar.com'))
  535.         self.assert_(is_HDN('1foo2.3bar4.5com'))
  536.         self.assert_(not is_HDN('192.168.1.1'))
  537.         self.assert_(not is_HDN(''))
  538.         self.assert_(not is_HDN('.'))
  539.         self.assert_(not is_HDN('.foo.bar.com'))
  540.         self.assert_(not is_HDN('..foo'))
  541.         self.assert_(not is_HDN('foo.'))
  542.  
  543.     
  544.     def test_reach(self):
  545.         reach = reach
  546.         import cookielib
  547.         self.assertEquals(reach('www.acme.com'), '.acme.com')
  548.         self.assertEquals(reach('acme.com'), 'acme.com')
  549.         self.assertEquals(reach('acme.local'), '.local')
  550.         self.assertEquals(reach('.local'), '.local')
  551.         self.assertEquals(reach('.com'), '.com')
  552.         self.assertEquals(reach('.'), '.')
  553.         self.assertEquals(reach(''), '')
  554.         self.assertEquals(reach('192.168.0.1'), '192.168.0.1')
  555.  
  556.     
  557.     def test_domain_match(self):
  558.         domain_match = domain_match
  559.         user_domain_match = user_domain_match
  560.         import cookielib
  561.         self.assert_(domain_match('192.168.1.1', '192.168.1.1'))
  562.         self.assert_(not domain_match('192.168.1.1', '.168.1.1'))
  563.         self.assert_(domain_match('x.y.com', 'x.Y.com'))
  564.         self.assert_(domain_match('x.y.com', '.Y.com'))
  565.         self.assert_(not domain_match('x.y.com', 'Y.com'))
  566.         self.assert_(domain_match('a.b.c.com', '.c.com'))
  567.         self.assert_(not domain_match('.c.com', 'a.b.c.com'))
  568.         self.assert_(domain_match('example.local', '.local'))
  569.         self.assert_(not domain_match('blah.blah', ''))
  570.         self.assert_(not domain_match('', '.rhubarb.rhubarb'))
  571.         self.assert_(domain_match('', ''))
  572.         self.assert_(user_domain_match('acme.com', 'acme.com'))
  573.         self.assert_(not user_domain_match('acme.com', '.acme.com'))
  574.         self.assert_(user_domain_match('rhubarb.acme.com', '.acme.com'))
  575.         self.assert_(user_domain_match('www.rhubarb.acme.com', '.acme.com'))
  576.         self.assert_(user_domain_match('x.y.com', 'x.Y.com'))
  577.         self.assert_(user_domain_match('x.y.com', '.Y.com'))
  578.         self.assert_(not user_domain_match('x.y.com', 'Y.com'))
  579.         self.assert_(user_domain_match('y.com', 'Y.com'))
  580.         self.assert_(not user_domain_match('.y.com', 'Y.com'))
  581.         self.assert_(user_domain_match('.y.com', '.Y.com'))
  582.         self.assert_(user_domain_match('x.y.com', '.com'))
  583.         self.assert_(not user_domain_match('x.y.com', 'com'))
  584.         self.assert_(not user_domain_match('x.y.com', 'm'))
  585.         self.assert_(not user_domain_match('x.y.com', '.m'))
  586.         self.assert_(not user_domain_match('x.y.com', ''))
  587.         self.assert_(not user_domain_match('x.y.com', '.'))
  588.         self.assert_(user_domain_match('192.168.1.1', '192.168.1.1'))
  589.         self.assert_(not user_domain_match('192.168.1.1', '.168.1.1'))
  590.         self.assert_(not user_domain_match('192.168.1.1', '.'))
  591.         self.assert_(not user_domain_match('192.168.1.1', ''))
  592.  
  593.     
  594.     def test_wrong_domain(self):
  595.         CookieJar = CookieJar
  596.         import cookielib
  597.         c = CookieJar()
  598.         interact_2965(c, 'http://www.nasty.com/', 'foo=bar; domain=friendly.org; Version="1"')
  599.         self.assertEquals(len(c), 0)
  600.  
  601.     
  602.     def test_two_component_domain_ns(self):
  603.         CookieJar = CookieJar
  604.         DefaultCookiePolicy = DefaultCookiePolicy
  605.         import cookielib
  606.         c = CookieJar()
  607.         interact_netscape(c, 'http://foo.net/', 'ns=bar')
  608.         self.assertEquals(len(c), 1)
  609.         self.assertEquals(c._cookies['foo.net']['/']['ns'].value, 'bar')
  610.         self.assertEquals(interact_netscape(c, 'http://foo.net/'), 'ns=bar')
  611.         self.assertEquals(interact_netscape(c, 'http://www.foo.net/'), 'ns=bar')
  612.         pol = DefaultCookiePolicy(strict_ns_domain = DefaultCookiePolicy.DomainStrictNonDomain)
  613.         c.set_policy(pol)
  614.         self.assertEquals(interact_netscape(c, 'http://www.foo.net/'), '')
  615.         interact_netscape(c, 'http://foo.net/foo/', 'spam1=eggs; domain=foo.net')
  616.         interact_netscape(c, 'http://foo.net/foo/bar/', 'spam2=eggs; domain=.foo.net')
  617.         self.assertEquals(len(c), 3)
  618.         self.assertEquals(c._cookies['.foo.net']['/foo']['spam1'].value, 'eggs')
  619.         self.assertEquals(c._cookies['.foo.net']['/foo/bar']['spam2'].value, 'eggs')
  620.         self.assertEquals(interact_netscape(c, 'http://foo.net/foo/bar/'), 'spam2=eggs; spam1=eggs; ns=bar')
  621.         interact_netscape(c, 'http://foo.net/', 'nini="ni"; domain=.net')
  622.         self.assertEquals(len(c), 3)
  623.         interact_netscape(c, 'http://foo.co.uk', 'nasty=trick; domain=.co.uk')
  624.         self.assertEquals(len(c), 4)
  625.  
  626.     
  627.     def test_two_component_domain_rfc2965(self):
  628.         CookieJar = CookieJar
  629.         DefaultCookiePolicy = DefaultCookiePolicy
  630.         import cookielib
  631.         pol = DefaultCookiePolicy(rfc2965 = True)
  632.         c = CookieJar(pol)
  633.         interact_2965(c, 'http://foo.net/', 'foo=bar; Version="1"')
  634.         self.assertEquals(len(c), 1)
  635.         self.assertEquals(c._cookies['foo.net']['/']['foo'].value, 'bar')
  636.         self.assertEquals(interact_2965(c, 'http://foo.net/'), '$Version=1; foo=bar')
  637.         self.assertEquals(interact_2965(c, 'http://www.foo.net/'), '')
  638.         interact_2965(c, 'http://foo.net/foo', 'spam=eggs; domain=foo.net; path=/foo; Version="1"')
  639.         self.assertEquals(len(c), 1)
  640.         self.assertEquals(interact_2965(c, 'http://foo.net/foo'), '$Version=1; foo=bar')
  641.         interact_2965(c, 'http://www.foo.net/foo/', 'spam=eggs; domain=foo.net; Version="1"')
  642.         self.assertEquals(c._cookies['.foo.net']['/foo/']['spam'].value, 'eggs')
  643.         self.assertEquals(len(c), 2)
  644.         self.assertEquals(interact_2965(c, 'http://foo.net/foo/'), '$Version=1; foo=bar')
  645.         self.assertEquals(interact_2965(c, 'http://www.foo.net/foo/'), '$Version=1; spam=eggs; $Domain="foo.net"')
  646.         interact_2965(c, 'http://foo.net/', 'ni="ni"; domain=".net"; Version="1"')
  647.         self.assertEquals(len(c), 2)
  648.         interact_2965(c, 'http://foo.co.uk/', 'nasty=trick; domain=.co.uk; Version="1"')
  649.         self.assertEquals(len(c), 3)
  650.  
  651.     
  652.     def test_domain_allow(self):
  653.         CookieJar = CookieJar
  654.         DefaultCookiePolicy = DefaultCookiePolicy
  655.         import cookielib
  656.         Request = Request
  657.         import urllib2
  658.         c = CookieJar(policy = DefaultCookiePolicy(blocked_domains = [
  659.             'acme.com'], allowed_domains = [
  660.             'www.acme.com']))
  661.         req = Request('http://acme.com/')
  662.         headers = [
  663.             'Set-Cookie: CUSTOMER=WILE_E_COYOTE; path=/']
  664.         res = FakeResponse(headers, 'http://acme.com/')
  665.         c.extract_cookies(res, req)
  666.         self.assertEquals(len(c), 0)
  667.         req = Request('http://www.acme.com/')
  668.         res = FakeResponse(headers, 'http://www.acme.com/')
  669.         c.extract_cookies(res, req)
  670.         self.assertEquals(len(c), 1)
  671.         req = Request('http://www.coyote.com/')
  672.         res = FakeResponse(headers, 'http://www.coyote.com/')
  673.         c.extract_cookies(res, req)
  674.         self.assertEquals(len(c), 1)
  675.         req = Request('http://www.coyote.com/')
  676.         res = FakeResponse(headers, 'http://www.coyote.com/')
  677.         cookies = c.make_cookies(res, req)
  678.         c.set_cookie(cookies[0])
  679.         self.assertEquals(len(c), 2)
  680.         c.add_cookie_header(req)
  681.         self.assert_(not req.has_header('Cookie'))
  682.  
  683.     
  684.     def test_domain_block(self):
  685.         CookieJar = CookieJar
  686.         DefaultCookiePolicy = DefaultCookiePolicy
  687.         import cookielib
  688.         Request = Request
  689.         import urllib2
  690.         pol = DefaultCookiePolicy(rfc2965 = True, blocked_domains = [
  691.             '.acme.com'])
  692.         c = CookieJar(policy = pol)
  693.         headers = [
  694.             'Set-Cookie: CUSTOMER=WILE_E_COYOTE; path=/']
  695.         req = Request('http://www.acme.com/')
  696.         res = FakeResponse(headers, 'http://www.acme.com/')
  697.         c.extract_cookies(res, req)
  698.         self.assertEquals(len(c), 0)
  699.         p = pol.set_blocked_domains([
  700.             'acme.com'])
  701.         c.extract_cookies(res, req)
  702.         self.assertEquals(len(c), 1)
  703.         c.clear()
  704.         req = Request('http://www.roadrunner.net/')
  705.         res = FakeResponse(headers, 'http://www.roadrunner.net/')
  706.         c.extract_cookies(res, req)
  707.         self.assertEquals(len(c), 1)
  708.         req = Request('http://www.roadrunner.net/')
  709.         c.add_cookie_header(req)
  710.         if req.has_header('Cookie'):
  711.             pass
  712.         self.assert_(req.has_header('Cookie2'))
  713.         c.clear()
  714.         pol.set_blocked_domains([
  715.             '.acme.com'])
  716.         c.extract_cookies(res, req)
  717.         self.assertEquals(len(c), 1)
  718.         req = Request('http://www.acme.com/')
  719.         res = FakeResponse(headers, 'http://www.acme.com/')
  720.         cookies = c.make_cookies(res, req)
  721.         c.set_cookie(cookies[0])
  722.         self.assertEquals(len(c), 2)
  723.         c.add_cookie_header(req)
  724.         self.assert_(not req.has_header('Cookie'))
  725.  
  726.     
  727.     def test_secure(self):
  728.         CookieJar = CookieJar
  729.         DefaultCookiePolicy = DefaultCookiePolicy
  730.         import cookielib
  731.         for ns in (True, False):
  732.             for whitespace in (' ', ''):
  733.                 c = CookieJar()
  734.                 if ns:
  735.                     pol = DefaultCookiePolicy(rfc2965 = False)
  736.                     int = interact_netscape
  737.                     vs = ''
  738.                 else:
  739.                     pol = DefaultCookiePolicy(rfc2965 = True)
  740.                     int = interact_2965
  741.                     vs = '; Version=1'
  742.                 c.set_policy(pol)
  743.                 url = 'http://www.acme.com/'
  744.                 int(c, url, 'foo1=bar%s%s' % (vs, whitespace))
  745.                 int(c, url, 'foo2=bar%s; secure%s' % (vs, whitespace))
  746.                 self.assert_(not (c._cookies['www.acme.com']['/']['foo1'].secure), 'non-secure cookie registered secure')
  747.                 self.assert_(c._cookies['www.acme.com']['/']['foo2'].secure, 'secure cookie registered non-secure')
  748.             
  749.         
  750.  
  751.     
  752.     def test_quote_cookie_value(self):
  753.         CookieJar = CookieJar
  754.         DefaultCookiePolicy = DefaultCookiePolicy
  755.         import cookielib
  756.         c = CookieJar(policy = DefaultCookiePolicy(rfc2965 = True))
  757.         interact_2965(c, 'http://www.acme.com/', 'foo=\\b"a"r; Version=1')
  758.         h = interact_2965(c, 'http://www.acme.com/')
  759.         self.assertEquals(h, '$Version=1; foo=\\\\b\\"a\\"r')
  760.  
  761.     
  762.     def test_missing_final_slash(self):
  763.         CookieJar = CookieJar
  764.         DefaultCookiePolicy = DefaultCookiePolicy
  765.         import cookielib
  766.         Request = Request
  767.         import urllib2
  768.         url = 'http://www.acme.com'
  769.         c = CookieJar(DefaultCookiePolicy(rfc2965 = True))
  770.         interact_2965(c, url, 'foo=bar; Version=1')
  771.         req = Request(url)
  772.         self.assertEquals(len(c), 1)
  773.         c.add_cookie_header(req)
  774.         self.assert_(req.has_header('Cookie'))
  775.  
  776.     
  777.     def test_domain_mirror(self):
  778.         CookieJar = CookieJar
  779.         DefaultCookiePolicy = DefaultCookiePolicy
  780.         import cookielib
  781.         pol = DefaultCookiePolicy(rfc2965 = True)
  782.         c = CookieJar(pol)
  783.         url = 'http://foo.bar.com/'
  784.         interact_2965(c, url, 'spam=eggs; Version=1')
  785.         h = interact_2965(c, url)
  786.         self.assert_('Domain' not in h, 'absent domain returned with domain present')
  787.         c = CookieJar(pol)
  788.         url = 'http://foo.bar.com/'
  789.         interact_2965(c, url, 'spam=eggs; Version=1; Domain=.bar.com')
  790.         h = interact_2965(c, url)
  791.         self.assert_('$Domain=".bar.com"' in h, 'domain not returned')
  792.         c = CookieJar(pol)
  793.         url = 'http://foo.bar.com/'
  794.         interact_2965(c, url, 'spam=eggs; Version=1; Domain=bar.com')
  795.         h = interact_2965(c, url)
  796.         self.assert_('$Domain="bar.com"' in h, 'domain not returned')
  797.  
  798.     
  799.     def test_path_mirror(self):
  800.         CookieJar = CookieJar
  801.         DefaultCookiePolicy = DefaultCookiePolicy
  802.         import cookielib
  803.         pol = DefaultCookiePolicy(rfc2965 = True)
  804.         c = CookieJar(pol)
  805.         url = 'http://foo.bar.com/'
  806.         interact_2965(c, url, 'spam=eggs; Version=1')
  807.         h = interact_2965(c, url)
  808.         self.assert_('Path' not in h, 'absent path returned with path present')
  809.         c = CookieJar(pol)
  810.         url = 'http://foo.bar.com/'
  811.         interact_2965(c, url, 'spam=eggs; Version=1; Path=/')
  812.         h = interact_2965(c, url)
  813.         self.assert_('$Path="/"' in h, 'path not returned')
  814.  
  815.     
  816.     def test_port_mirror(self):
  817.         CookieJar = CookieJar
  818.         DefaultCookiePolicy = DefaultCookiePolicy
  819.         import cookielib
  820.         pol = DefaultCookiePolicy(rfc2965 = True)
  821.         c = CookieJar(pol)
  822.         url = 'http://foo.bar.com/'
  823.         interact_2965(c, url, 'spam=eggs; Version=1')
  824.         h = interact_2965(c, url)
  825.         self.assert_('Port' not in h, 'absent port returned with port present')
  826.         c = CookieJar(pol)
  827.         url = 'http://foo.bar.com/'
  828.         interact_2965(c, url, 'spam=eggs; Version=1; Port')
  829.         h = interact_2965(c, url)
  830.         self.assert_(re.search('\\$Port([^=]|$)', h), 'port with no value not returned with no value')
  831.         c = CookieJar(pol)
  832.         url = 'http://foo.bar.com/'
  833.         interact_2965(c, url, 'spam=eggs; Version=1; Port="80"')
  834.         h = interact_2965(c, url)
  835.         self.assert_('$Port="80"' in h, 'port with single value not returned with single value')
  836.         c = CookieJar(pol)
  837.         url = 'http://foo.bar.com/'
  838.         interact_2965(c, url, 'spam=eggs; Version=1; Port="80,8080"')
  839.         h = interact_2965(c, url)
  840.         self.assert_('$Port="80,8080"' in h, 'port with multiple values not returned with multiple values')
  841.  
  842.     
  843.     def test_no_return_comment(self):
  844.         CookieJar = CookieJar
  845.         DefaultCookiePolicy = DefaultCookiePolicy
  846.         import cookielib
  847.         c = CookieJar(DefaultCookiePolicy(rfc2965 = True))
  848.         url = 'http://foo.bar.com/'
  849.         interact_2965(c, url, 'spam=eggs; Version=1; Comment="does anybody read these?"; CommentURL="http://foo.bar.net/comment.html"')
  850.         h = interact_2965(c, url)
  851.         self.assert_('Comment' not in h, 'Comment or CommentURL cookie-attributes returned to server')
  852.  
  853.     
  854.     def test_Cookie_iterator(self):
  855.         CookieJar = CookieJar
  856.         Cookie = Cookie
  857.         DefaultCookiePolicy = DefaultCookiePolicy
  858.         import cookielib
  859.         cs = CookieJar(DefaultCookiePolicy(rfc2965 = True))
  860.         interact_2965(cs, 'http://blah.spam.org/', 'foo=eggs; Version=1; Comment="does anybody read these?"; CommentURL="http://foo.bar.net/comment.html"')
  861.         interact_netscape(cs, 'http://www.acme.com/blah/', 'spam=bar; secure')
  862.         interact_2965(cs, 'http://www.acme.com/blah/', 'foo=bar; secure; Version=1')
  863.         interact_2965(cs, 'http://www.acme.com/blah/', 'foo=bar; path=/; Version=1')
  864.         interact_2965(cs, 'http://www.sol.no', 'bang=wallop; version=1; domain=".sol.no"; port="90,100, 80,8080"; max-age=100; Comment = "Just kidding! (\\"|\\\\\\\\) "')
  865.         versions = [
  866.             1,
  867.             1,
  868.             1,
  869.             0,
  870.             1]
  871.         names = [
  872.             'bang',
  873.             'foo',
  874.             'foo',
  875.             'spam',
  876.             'foo']
  877.         domains = [
  878.             '.sol.no',
  879.             'blah.spam.org',
  880.             'www.acme.com',
  881.             'www.acme.com',
  882.             'www.acme.com']
  883.         paths = [
  884.             '/',
  885.             '/',
  886.             '/',
  887.             '/blah',
  888.             '/blah/']
  889.         for i in range(4):
  890.             i = 0
  891.             for c in cs:
  892.                 self.assert_(isinstance(c, Cookie))
  893.                 self.assertEquals(c.version, versions[i])
  894.                 self.assertEquals(c.name, names[i])
  895.                 self.assertEquals(c.domain, domains[i])
  896.                 self.assertEquals(c.path, paths[i])
  897.                 i = i + 1
  898.             
  899.         
  900.  
  901.     
  902.     def test_parse_ns_headers(self):
  903.         parse_ns_headers = parse_ns_headers
  904.         import cookielib
  905.         self.assertEquals(parse_ns_headers([
  906.             'foo=bar; path=/; domain']), [
  907.             [
  908.                 ('foo', 'bar'),
  909.                 ('path', '/'),
  910.                 ('domain', None),
  911.                 ('version', '0')]])
  912.         self.assertEquals(parse_ns_headers([
  913.             'foo=bar; expires=Foo Bar 12 33:22:11 2000']), [
  914.             [
  915.                 ('foo', 'bar'),
  916.                 ('expires', None),
  917.                 ('version', '0')]])
  918.         self.assertEquals(parse_ns_headers([
  919.             'foo']), [
  920.             [
  921.                 ('foo', None),
  922.                 ('version', '0')]])
  923.         self.assertEquals(parse_ns_headers([
  924.             '']), [])
  925.  
  926.     
  927.     def test_bad_cookie_header(self):
  928.         
  929.         def cookiejar_from_cookie_headers(headers):
  930.             CookieJar = CookieJar
  931.             import cookielib
  932.             Request = Request
  933.             import urllib2
  934.             c = CookieJar()
  935.             req = Request('http://www.example.com/')
  936.             r = FakeResponse(headers, 'http://www.example.com/')
  937.             c.extract_cookies(r, req)
  938.             return c
  939.  
  940.         for headers in [
  941.             [
  942.                 'Set-Cookie: '],
  943.             [
  944.                 'Set-Cookie2: '],
  945.             [
  946.                 'Set-Cookie2: a=foo; path=/; Version=1; domain'],
  947.             [
  948.                 'Set-Cookie: b=foo; max-age=oops']]:
  949.             c = cookiejar_from_cookie_headers(headers)
  950.             self.assertEquals(len(c), 0)
  951.         
  952.         headers = [
  953.             'Set-Cookie: c=foo; expires=Foo Bar 12 33:22:11 2000']
  954.         c = cookiejar_from_cookie_headers(headers)
  955.         cookie = c._cookies['www.example.com']['/']['c']
  956.         self.assert_(cookie.expires is None)
  957.  
  958.  
  959.  
  960. class LWPCookieTests(TestCase):
  961.     
  962.     def test_netscape_example_1(self):
  963.         CookieJar = CookieJar
  964.         DefaultCookiePolicy = DefaultCookiePolicy
  965.         import cookielib
  966.         Request = Request
  967.         import urllib2
  968.         year_plus_one = time.localtime()[0] + 1
  969.         headers = []
  970.         c = CookieJar(DefaultCookiePolicy(rfc2965 = True))
  971.         req = Request('http://www.acme.com:80/', headers = {
  972.             'Host': 'www.acme.com:80' })
  973.         headers.append('Set-Cookie: CUSTOMER=WILE_E_COYOTE; path=/ ; expires=Wednesday, 09-Nov-%d 23:12:40 GMT' % year_plus_one)
  974.         res = FakeResponse(headers, 'http://www.acme.com/')
  975.         c.extract_cookies(res, req)
  976.         req = Request('http://www.acme.com/')
  977.         c.add_cookie_header(req)
  978.         self.assertEqual(req.get_header('Cookie'), 'CUSTOMER=WILE_E_COYOTE')
  979.         self.assertEqual(req.get_header('Cookie2'), '$Version="1"')
  980.         headers.append('Set-Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001; path=/')
  981.         res = FakeResponse(headers, 'http://www.acme.com/')
  982.         c.extract_cookies(res, req)
  983.         req = Request('http://www.acme.com/foo/bar')
  984.         c.add_cookie_header(req)
  985.         h = req.get_header('Cookie')
  986.         if 'PART_NUMBER=ROCKET_LAUNCHER_0001' in h:
  987.             pass
  988.         self.assert_('CUSTOMER=WILE_E_COYOTE' in h)
  989.         headers.append('Set-Cookie: SHIPPING=FEDEX; path=/foo')
  990.         res = FakeResponse(headers, 'http://www.acme.com')
  991.         c.extract_cookies(res, req)
  992.         req = Request('http://www.acme.com/')
  993.         c.add_cookie_header(req)
  994.         h = req.get_header('Cookie')
  995.         if 'PART_NUMBER=ROCKET_LAUNCHER_0001' in h and 'CUSTOMER=WILE_E_COYOTE' in h:
  996.             pass
  997.         self.assert_('SHIPPING=FEDEX' not in h)
  998.         req = Request('http://www.acme.com/foo/')
  999.         c.add_cookie_header(req)
  1000.         h = req.get_header('Cookie')
  1001.         if 'PART_NUMBER=ROCKET_LAUNCHER_0001' in h and 'CUSTOMER=WILE_E_COYOTE' in h:
  1002.             pass
  1003.         self.assert_(h.startswith('SHIPPING=FEDEX;'))
  1004.  
  1005.     
  1006.     def test_netscape_example_2(self):
  1007.         CookieJar = CookieJar
  1008.         import cookielib
  1009.         Request = Request
  1010.         import urllib2
  1011.         c = CookieJar()
  1012.         headers = []
  1013.         req = Request('http://www.acme.com/')
  1014.         headers.append('Set-Cookie: PART_NUMBER=ROCKET_LAUNCHER_0001; path=/')
  1015.         res = FakeResponse(headers, 'http://www.acme.com/')
  1016.         c.extract_cookies(res, req)
  1017.         req = Request('http://www.acme.com/')
  1018.         c.add_cookie_header(req)
  1019.         self.assertEquals(req.get_header('Cookie'), 'PART_NUMBER=ROCKET_LAUNCHER_0001')
  1020.         headers.append('Set-Cookie: PART_NUMBER=RIDING_ROCKET_0023; path=/ammo')
  1021.         res = FakeResponse(headers, 'http://www.acme.com/')
  1022.         c.extract_cookies(res, req)
  1023.         req = Request('http://www.acme.com/ammo')
  1024.         c.add_cookie_header(req)
  1025.         self.assert_(re.search('PART_NUMBER=RIDING_ROCKET_0023;\\s*PART_NUMBER=ROCKET_LAUNCHER_0001', req.get_header('Cookie')))
  1026.  
  1027.     
  1028.     def test_ietf_example_1(self):
  1029.         CookieJar = CookieJar
  1030.         DefaultCookiePolicy = DefaultCookiePolicy
  1031.         import cookielib
  1032.         c = CookieJar(DefaultCookiePolicy(rfc2965 = True))
  1033.         cookie = interact_2965(c, 'http://www.acme.com/acme/login', 'Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"')
  1034.         self.assert_(not cookie)
  1035.         cookie = interact_2965(c, 'http://www.acme.com/acme/pickitem', 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"')
  1036.         self.assert_(re.search('^\\$Version="?1"?; Customer="?WILE_E_COYOTE"?; \\$Path="/acme"$', cookie))
  1037.         cookie = interact_2965(c, 'http://www.acme.com/acme/shipping', 'Shipping="FedEx"; Version="1"; Path="/acme"')
  1038.         self.assert_(re.search('^\\$Version="?1"?;', cookie))
  1039.         self.assert_(re.search('Part_Number="?Rocket_Launcher_0001"?;\\s*\\$Path="\\/acme"', cookie))
  1040.         self.assert_(re.search('Customer="?WILE_E_COYOTE"?;\\s*\\$Path="\\/acme"', cookie))
  1041.         cookie = interact_2965(c, 'http://www.acme.com/acme/process')
  1042.         if re.search('Shipping="?FedEx"?;\\s*\\$Path="\\/acme"', cookie):
  1043.             pass
  1044.         self.assert_('WILE_E_COYOTE' in cookie)
  1045.  
  1046.     
  1047.     def test_ietf_example_2(self):
  1048.         CookieJar = CookieJar
  1049.         DefaultCookiePolicy = DefaultCookiePolicy
  1050.         import cookielib
  1051.         c = CookieJar(DefaultCookiePolicy(rfc2965 = True))
  1052.         interact_2965(c, 'http://www.acme.com/acme/ammo/specific', 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"', 'Part_Number="Riding_Rocket_0023"; Version="1"; Path="/acme/ammo"')
  1053.         cookie = interact_2965(c, 'http://www.acme.com/acme/ammo/...')
  1054.         self.assert_(re.search('Riding_Rocket_0023.*Rocket_Launcher_0001', cookie))
  1055.         cookie = interact_2965(c, 'http://www.acme.com/acme/parts/')
  1056.         if 'Rocket_Launcher_0001' in cookie:
  1057.             pass
  1058.         self.assert_('Riding_Rocket_0023' not in cookie)
  1059.  
  1060.     
  1061.     def test_rejection(self):
  1062.         DefaultCookiePolicy = DefaultCookiePolicy
  1063.         LWPCookieJar = LWPCookieJar
  1064.         import cookielib
  1065.         pol = DefaultCookiePolicy(rfc2965 = True)
  1066.         c = LWPCookieJar(policy = pol)
  1067.         max_age = 'max-age=3600'
  1068.         cookie = interact_2965(c, 'http://www.acme.com', 'foo=bar; domain=".com"; version=1')
  1069.         self.assert_(not c)
  1070.         cookie = interact_2965(c, 'http://www.acme.com', 'ping=pong; domain="acme.com"; version=1')
  1071.         self.assertEquals(len(c), 1)
  1072.         cookie = interact_2965(c, 'http://www.a.acme.com', 'whiz=bang; domain="acme.com"; version=1')
  1073.         self.assertEquals(len(c), 1)
  1074.         cookie = interact_2965(c, 'http://www.a.acme.com', 'wow=flutter; domain=".a.acme.com"; version=1')
  1075.         self.assertEquals(len(c), 2)
  1076.         cookie = interact_2965(c, 'http://125.125.125.125', 'zzzz=ping; domain="125.125.125"; version=1')
  1077.         self.assertEquals(len(c), 2)
  1078.         cookie = interact_2965(c, 'http://www.sol.no', 'blah=rhubarb; domain=".sol.no"; path="/foo"; version=1')
  1079.         self.assertEquals(len(c), 2)
  1080.         cookie = interact_2965(c, 'http://www.sol.no/foo/bar', 'bing=bong; domain=".sol.no"; path="/foo"; version=1')
  1081.         self.assertEquals(len(c), 3)
  1082.         cookie = interact_2965(c, 'http://www.sol.no', 'whiz=ffft; domain=".sol.no"; port="90,100"; version=1')
  1083.         self.assertEquals(len(c), 3)
  1084.         cookie = interact_2965(c, 'http://www.sol.no', 'bang=wallop; version=1; domain=".sol.no"; port="90,100, 80,8080"; max-age=100; Comment = "Just kidding! (\\"|\\\\\\\\) "')
  1085.         self.assertEquals(len(c), 4)
  1086.         cookie = interact_2965(c, 'http://www.sol.no', 'foo9=bar; version=1; domain=".sol.no"; port; max-age=100;')
  1087.         self.assertEquals(len(c), 5)
  1088.         cookie = interact_2965(c, 'http://www.sol.no/<oo/', 'foo8=bar; version=1; path="/%3coo"')
  1089.         self.assertEquals(len(c), 6)
  1090.         filename = test_support.TESTFN
  1091.         
  1092.         try:
  1093.             c.save(filename, ignore_discard = True)
  1094.             old = repr(c)
  1095.             c = LWPCookieJar(policy = pol)
  1096.             c.load(filename, ignore_discard = True)
  1097.         finally:
  1098.             
  1099.             try:
  1100.                 os.unlink(filename)
  1101.             except OSError:
  1102.                 pass
  1103.  
  1104.  
  1105.         self.assertEquals(old, repr(c))
  1106.  
  1107.     
  1108.     def test_url_encoding(self):
  1109.         CookieJar = CookieJar
  1110.         DefaultCookiePolicy = DefaultCookiePolicy
  1111.         import cookielib
  1112.         c = CookieJar(DefaultCookiePolicy(rfc2965 = True))
  1113.         interact_2965(c, 'http://www.acme.com/foo%2f%25/%3c%3c%0Anew%E5/%E5', 'foo  =   bar; version    =   1')
  1114.         cookie = interact_2965(c, 'http://www.acme.com/foo%2f%25/<<%0anew\xe5/\xe6\xf8\xe5', 'bar=baz; path="/foo/"; version=1')
  1115.         version_re = re.compile('^\\$version=\\"?1\\"?', re.I)
  1116.         if 'foo=bar' in cookie:
  1117.             pass
  1118.         self.assert_(version_re.search(cookie))
  1119.         cookie = interact_2965(c, 'http://www.acme.com/foo/%25/<<%0anew\xe5/\xe6\xf8\xe5')
  1120.         self.assert_(not cookie)
  1121.         cookie = interact_2965(c, u'http://www.acme.com/\xc3\xbc')
  1122.  
  1123.     
  1124.     def test_mozilla(self):
  1125.         MozillaCookieJar = MozillaCookieJar
  1126.         DefaultCookiePolicy = DefaultCookiePolicy
  1127.         import cookielib
  1128.         year_plus_one = time.localtime()[0] + 1
  1129.         filename = test_support.TESTFN
  1130.         c = MozillaCookieJar(filename, policy = DefaultCookiePolicy(rfc2965 = True))
  1131.         interact_2965(c, 'http://www.acme.com/', 'foo1=bar; max-age=100; Version=1')
  1132.         interact_2965(c, 'http://www.acme.com/', 'foo2=bar; port="80"; max-age=100; Discard; Version=1')
  1133.         interact_2965(c, 'http://www.acme.com/', 'foo3=bar; secure; Version=1')
  1134.         expires = 'expires=09-Nov-%d 23:12:40 GMT' % (year_plus_one,)
  1135.         interact_netscape(c, 'http://www.foo.com/', 'fooa=bar; %s' % expires)
  1136.         interact_netscape(c, 'http://www.foo.com/', 'foob=bar; Domain=.foo.com; %s' % expires)
  1137.         interact_netscape(c, 'http://www.foo.com/', 'fooc=bar; Domain=www.foo.com; %s' % expires)
  1138.         
  1139.         def save_and_restore(cj, ignore_discard):
  1140.             
  1141.             try:
  1142.                 cj.save(ignore_discard = ignore_discard)
  1143.                 new_c = MozillaCookieJar(filename, DefaultCookiePolicy(rfc2965 = True))
  1144.                 new_c.load(ignore_discard = ignore_discard)
  1145.             finally:
  1146.                 
  1147.                 try:
  1148.                     os.unlink(filename)
  1149.                 except OSError:
  1150.                     pass
  1151.  
  1152.  
  1153.             return new_c
  1154.  
  1155.         new_c = save_and_restore(c, True)
  1156.         self.assertEquals(len(new_c), 6)
  1157.         self.assert_("name='foo1', value='bar'" in repr(new_c))
  1158.         new_c = save_and_restore(c, False)
  1159.         self.assertEquals(len(new_c), 4)
  1160.         self.assert_("name='foo1', value='bar'" in repr(new_c))
  1161.  
  1162.     
  1163.     def test_netscape_misc(self):
  1164.         CookieJar = CookieJar
  1165.         import cookielib
  1166.         Request = Request
  1167.         import urllib2
  1168.         c = CookieJar()
  1169.         headers = []
  1170.         req = Request('http://foo.bar.acme.com/foo')
  1171.         headers.append('Set-Cookie: Customer=WILE_E_COYOTE; domain=.acme.com')
  1172.         res = FakeResponse(headers, 'http://www.acme.com/foo')
  1173.         c.extract_cookies(res, req)
  1174.         headers.append('Set-Cookie: PART_NUMBER=3,4; domain=foo.bar.acme.com')
  1175.         res = FakeResponse(headers, 'http://www.acme.com/foo')
  1176.         c.extract_cookies(res, req)
  1177.         req = Request('http://foo.bar.acme.com/foo')
  1178.         c.add_cookie_header(req)
  1179.         if 'PART_NUMBER=3,4' in req.get_header('Cookie'):
  1180.             pass
  1181.         self.assert_('Customer=WILE_E_COYOTE' in req.get_header('Cookie'))
  1182.  
  1183.     
  1184.     def test_intranet_domains_2965(self):
  1185.         CookieJar = CookieJar
  1186.         DefaultCookiePolicy = DefaultCookiePolicy
  1187.         import cookielib
  1188.         c = CookieJar(DefaultCookiePolicy(rfc2965 = True))
  1189.         interact_2965(c, 'http://example/', 'foo1=bar; PORT; Discard; Version=1;')
  1190.         cookie = interact_2965(c, 'http://example/', 'foo2=bar; domain=".local"; Version=1')
  1191.         self.assert_('foo1=bar' in cookie)
  1192.         interact_2965(c, 'http://example/', 'foo3=bar; Version=1')
  1193.         cookie = interact_2965(c, 'http://example/')
  1194.         if 'foo2=bar' in cookie:
  1195.             pass
  1196.         self.assert_(len(c) == 3)
  1197.  
  1198.     
  1199.     def test_intranet_domains_ns(self):
  1200.         CookieJar = CookieJar
  1201.         DefaultCookiePolicy = DefaultCookiePolicy
  1202.         import cookielib
  1203.         c = CookieJar(DefaultCookiePolicy(rfc2965 = False))
  1204.         interact_netscape(c, 'http://example/', 'foo1=bar')
  1205.         cookie = interact_netscape(c, 'http://example/', 'foo2=bar; domain=.local')
  1206.         self.assertEquals(len(c), 2)
  1207.         self.assert_('foo1=bar' in cookie)
  1208.         cookie = interact_netscape(c, 'http://example/')
  1209.         self.assert_('foo2=bar' in cookie)
  1210.         self.assertEquals(len(c), 2)
  1211.  
  1212.     
  1213.     def test_empty_path(self):
  1214.         CookieJar = CookieJar
  1215.         DefaultCookiePolicy = DefaultCookiePolicy
  1216.         import cookielib
  1217.         Request = Request
  1218.         import urllib2
  1219.         c = CookieJar(DefaultCookiePolicy(rfc2965 = True))
  1220.         headers = []
  1221.         req = Request('http://www.ants.com/')
  1222.         headers.append('Set-Cookie: JSESSIONID=ABCDERANDOM123; Path=')
  1223.         res = FakeResponse(headers, 'http://www.ants.com/')
  1224.         c.extract_cookies(res, req)
  1225.         req = Request('http://www.ants.com/')
  1226.         c.add_cookie_header(req)
  1227.         self.assertEquals(req.get_header('Cookie'), 'JSESSIONID=ABCDERANDOM123')
  1228.         self.assertEquals(req.get_header('Cookie2'), '$Version="1"')
  1229.         req = Request('http://www.ants.com:8080')
  1230.         c.add_cookie_header(req)
  1231.         self.assertEquals(req.get_header('Cookie'), 'JSESSIONID=ABCDERANDOM123')
  1232.         self.assertEquals(req.get_header('Cookie2'), '$Version="1"')
  1233.  
  1234.     
  1235.     def test_session_cookies(self):
  1236.         CookieJar = CookieJar
  1237.         import cookielib
  1238.         Request = Request
  1239.         import urllib2
  1240.         year_plus_one = time.localtime()[0] + 1
  1241.         req = Request('http://www.perlmeister.com/scripts')
  1242.         headers = []
  1243.         headers.append('Set-Cookie: s1=session;Path=/scripts')
  1244.         headers.append('Set-Cookie: p1=perm; Domain=.perlmeister.com;Path=/;expires=Fri, 02-Feb-%d 23:24:20 GMT' % year_plus_one)
  1245.         headers.append('Set-Cookie: p2=perm;Path=/;expires=Fri, 02-Feb-%d 23:24:20 GMT' % year_plus_one)
  1246.         headers.append('Set-Cookie: s2=session;Path=/scripts;Domain=.perlmeister.com')
  1247.         headers.append('Set-Cookie2: s3=session;Version=1;Discard;Path="/"')
  1248.         res = FakeResponse(headers, 'http://www.perlmeister.com/scripts')
  1249.         c = CookieJar()
  1250.         c.extract_cookies(res, req)
  1251.         counter = {
  1252.             'session_after': 0,
  1253.             'perm_after': 0,
  1254.             'session_before': 0,
  1255.             'perm_before': 0 }
  1256.         for cookie in c:
  1257.             key = '%s_before' % cookie.value
  1258.             counter[key] = counter[key] + 1
  1259.         
  1260.         c.clear_session_cookies()
  1261.         for cookie in c:
  1262.             key = '%s_after' % cookie.value
  1263.             counter[key] = counter[key] + 1
  1264.         
  1265.         if not counter['perm_after'] != counter['perm_before'] and counter['session_after'] != 0:
  1266.             pass
  1267.         self.assert_(not (counter['session_before'] == 0))
  1268.  
  1269.  
  1270.  
  1271. def test_main(verbose = None):
  1272.     test_sets = test_sets
  1273.     import test
  1274.     test_support.run_unittest(DateTimeTests, HeaderTests, CookieTests, FileCookieJarTests, LWPCookieTests)
  1275.  
  1276. if __name__ == '__main__':
  1277.     test_main(verbose = True)
  1278.  
  1279.